package indi.caibo.vod.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import indi.caibo.servicebase.exceptionhandler.GuliException;
import indi.caibo.vod.service.VideoService;
import indi.caibo.vod.utils.AliyunVodSDKUtils;
import indi.caibo.vod.utils.ConstantPropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author Bo Cai
 * @version 1.0
 * @date 2021/10/8 21:14
 */
@Service
@Slf4j
public class VideoServiceImpl implements VideoService {
    @Override
    public String uploadVideo(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String title = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            System.out.println(ConstantPropertiesUtil.ACCESS_KEY_ID);
            System.out.println(ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            UploadStreamRequest request = new UploadStreamRequest(
                    ConstantPropertiesUtil.ACCESS_KEY_ID,
                    ConstantPropertiesUtil.ACCESS_KEY_SECRET,
                    title, originalFilename, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。
            // 其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            String videoId = response.getVideoId();
            if (!response.isSuccess()) {
                String errorMessage = "阿里云上传错误：" + "code：" + response.getCode() + ", message：" + response.getMessage();
                log.warn(errorMessage);
                if (StringUtils.isEmpty(videoId)) {
                    throw new GuliException(20001, errorMessage);
                }
            }
            return videoId;
        } catch (IOException e) {
            throw new GuliException(20001, "guli vod 服务上传失败");
        }
    }

    @Override
    public void removeVideo(String videoId) {
        try {
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
                    ConstantPropertiesUtil.ACCESS_KEY_ID,
                    ConstantPropertiesUtil.ACCESS_KEY_SECRET);
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoId);
            DeleteVideoResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            throw new GuliException(20001, "视频删除失败");
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void removeVideoList(List<String> videoIdList){
        // 初始化
        DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
                ConstantPropertiesUtil.ACCESS_KEY_ID,
                ConstantPropertiesUtil.ACCESS_KEY_SECRET);
        DeleteVideoRequest request = new DeleteVideoRequest();
        int size = videoIdList.size(); // id列表的长度
        StringBuffer idListStr = new StringBuffer(); //组装好的字符串
        for (int i = 1; i <= size; i++) {
            idListStr.append(videoIdList.get(i - 1));
            if (i == size || i % 20 == 0) { // 当是最后一个或是20的倍数，就开始批量删除
                // 删除，支持传入多个视频ID，多个用逗号分隔。id不能超过20个
                log.info("idListStr = " + idListStr.toString());
                request.setVideoIds(idListStr.toString());
                try {
                    client.getAcsResponse(request);
                } catch (com.aliyuncs.exceptions.ClientException e) {
                    e.printStackTrace();
                }
                // 重置idListStr
                idListStr = new StringBuffer();
            } else {
                idListStr.append(",");
            }
        }

    }
}
